=begin pod :tag<perl6>

=TITLE Operators

=SUBTITLE Common Perl 6 infixes, prefixes, postfixes, and more!

See L<Sub> on how to define operators.

=head1 Operator Precedence

In an expression like C<1 + 2 * 3>, the C<2 * 3> is evaluated first
because the infix C<*> has tighter B<precedence> than the C<+>.

The following table summarizes the precedence levels in Perl 6, from
tightest to loosest:

=begin table

    A | Level            |   Examples
    ==+==================+==========
    N | Terms            |   42 3.14 "eek" qq["foo"] $x :!verbose @$array
    L | Method postfix   |   .meth .\+ .? .* .() .[] .{} .<> .«» .:: .= .^ .:
    N | Autoincrement    |   \+\+ --
    R | Exponentiation   |   **
    L | Symbolic unary   |   ! \+ - ~ ? \| \|\| \+^ ~^ ?^ ^
    L | Dotty infix      |   .= .
    L | Multiplicative   |   * / % %% \+& \+< \+> ~& ~< ~> ?& div mod gcd lcm
    L | Additive         |   \+ - \+\| \+^ ~\| ~^ ?\| ?^
    L | Replication      |   x xx
    X | Concatenation    |   ~
    X | Junctive and     |   &
    X | Junctive or      |   \| ^
    L | Named unary      |   temp let
    N | Structural infix |   but does <=> leg cmp .. ..^ ^.. ^..^
    C | Chaining infix   |   != == < <= > >= eq ne lt le gt ge ~~ === eqv !eqv =~=
    X | Tight and        |   &&
    X | Tight or         |   \|\| ^^ // min max
    R | Conditional      |   ?? !! ff fff
    R | Item assignment  |   = => \+= -= **= xx=
    L | Loose unary      |   so not
    X | Comma operator   |   , :
    X | List infix       |   Z minmax X X~ X* Xeqv ...
    R | List prefix      |   print push say die map substr ... [\+] [*] any Z=
    X | Loose and        |   and andthen notandthen
    X | Loose or         |   or xor orelse
    X | Sequencer        |   <==, ==>, <<==, ==>>
    N | Terminator       |   ; {...}, unless, extra ), ], }

=end table

Using two C<!> symbols below generically to represent any pair of operators
that have the same precedence, the associativities specified above
for binary operators are interpreted as follows:

=begin table

    A  | Assoc   | Meaning of $a ! $b ! $c
    ===+=========+========================
    L  | left    |  ($a ! $b) ! $c
    R  | right   |  $a ! ($b ! $c)
    N  | non     |  ILLEGAL
    C  | chain   |  ($a ! $b) and ($b ! $c)
    X  | list    |  infix:<!>($a; $b; $c)

=end table

For unary operators this is interpreted as:

=begin table

    A  | Assoc   |  Meaning of !$a!
    ===+=========+==========================
    L  | left    |  (!$a)!
    R  | right   |  !($a!)
    N  | non     |  ILLEGAL

=end table

In the operator descriptions below, a default associativity of I<left>
is assumed.

=head1 Operator classification

X<|prefix operator>
X<|infix operator>
X<|postfix operator>
X<|circumfix operator>
X<|postcircumfix operator>

Operators can occur in several positions relative to a term:

=begin table

    \+term          | prefix
    term1 \+ term2  | infix
    term\+\+        | postfix
    (term)          | circumfix
    term1[term2]    | postcircumfix

=end table

Each operator is also available as a subroutine.
The name of the routine is formed from
the operator category, followed by a colon, then a list quote construct with the
symbol(s) that make up the operator:

    infix:<+>(1, 2);                # same as 1 + 2
    circumfix:«[ ]»(<a b c>);       # same as [<a b c>]

As a special case, a I<listop> (list operator) can stand either as a
term or as a prefix. Subroutine calls are the most common listops. Other
cases include meta-reduced infix operators (C<[+] 1, 2, 3>) and the
L<#prefix ...> etc. stub operators.


Defining custom operators is covered in
L<Defining Operators functions|/language/functions#Defining_Operators>.

=head1 Meta Operators

Meta operators can be parameterized with other operators or subroutines in the
same way as functions can take functions as parameters. To use a subroutine as
a parameter, prefix its name with a C<&>. Perl 6 will generate the actual
combined operator in the background, allowing the mechanism to be applied to
user defined operators. To disambiguate chained meta operators, enclose the
inner operator in square brackets. There are quite a few Meta operators with
different semantics as explained, next.

=head1 Substitution Operators

=head2 C<s///> in-place substitution

    my $str = 'old string';
    $str ~~ s/o .+ d/new/;
    say $str; # OUTPUT: «new string␤»

C<s///> operates on the C<$_> topical variable, changing it in
place. It uses the given
L«C<Regex>|/type/Regex» to find portions to replace and changes them to the
provided replacement string. Sets C<$/> to the L«C<Match>|/type/Match» object
or, if multiple matches were made, a L«C<List>|/type/List» of C<Match> objects.
Returns C<$/>.

It's common to use this operator with the C<~~> smartmatch operator, as it
aliases left hand side to C<$_>, which C<s///> uses.

Regex captures can be referenced in the replacement part; it takes the same
adverbs as the L«C<.subst> method|/routine/subst», which go between the C<s>
and the opening C</>, separated with optional whitespace:

    my $str = 'foo muCKed into the lEn';

    # replace second 'o' with 'x'
    $str ~~ s:2nd/o/x/;

    # replace 'M' or 'L' followed by non-whitespace stuff with 'd'
    # and lower-cased version of that stuff:
    $str ~~ s :g :i/<[ML]> (\S+)/d{lc $0}/;

    say $str; # OUTPUT: «fox ducked into the den␤»

You can also use a different delimiter:

    my $str = 'foober';
    $str ~~ s!foo!fox!;
    $str ~~ s{b(.)r} = " d$0n";
    say $str; # OUTPUT: «fox den␤»

Non-paired characters can simply replace the original slashes. Paired
characters, like braces, are used only on the match portion, with the
substitution given by assignment (of anything: a string, a routine call, etc.).

=head2 C<S///> non-destructive substitution

    say S/o .+ d/new/ with 'old string';      # OUTPUT: «new string␤»
    S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «Foo␤Bar␤Ber␤»

C<S///> uses the same semantics as the C<s///> operator, except
it leaves the original string intact
and I<returns the resultant string> instead of C<$/> (C<$/> still being set
to the same values as with C<s///>).

B<Note:> since the result is obtained as a return value, using this
operator with the C<~~> smartmatch operator is a mistake and will issue a
warning. To execute the substitution on a variable that isn't the C<$_> this
operator uses, alias it to C<$_> with C<given>, C<with>, or any other way.
Alternatively, use the L«C<.subst> method|/routine/subst».

=head2 C<tr///> in-place transliteration

    my $str = 'old string';
    $str ~~ tr/dol/wne/;
    say $str; # OUTPUT: «new string␤»

C<tr///> operates on the C<$_> topical variable and changes it in place.
It behaves similar to
L«C<Str.trans>|/routine/trans» called with a single L<Pair> argument, where
key is the matching part (characters C<dol> in the example above) and value is
the replacement part (characters C<wne> in the example above). Accepts the
same adverbs as L«C<Str.trans>|/routine/trans». Returns the L<StrDistance> object
that measures the distance between original value and the resultant string.

    my $str = 'old string';
    $str ~~ tr:c:d/dol st//;
    say $str; # OUTPUT: «ring␤»

=head2 C<TR///> non-destructive transliteration

    with 'old string' {
        say TR/dol/wne/; # OUTPUT: «new string␤»
    }

C<TR///> behaves the same as the C<tr///> operator,
except that it leaves the C<$_>
value untouched and instead returns the resultant string.

    say TR:d/dol // with 'old string'; # OUTPUT: «string␤»

=head1 Assignment Operators

Infix operators can be combined with the assignment operator to modify a
value and apply the result to a container in one go. Containers will be
autovivified if possible. Some examples:

    my $a = 32;
    $a += 10;     # 42
    $a -= 2;      # 40

    $a = 3;
    $a min= 5;    # still 3
    $a min= 2;    # 2

    my $s = 'a';
    $s ~= 'b';    # 'ab'

This behavior is automatically extended to include custom-defined infix operators.

    sub infix:<space-concat> ($a, $b) { $a ~ " " ~ $b };
    my $a = 'word1';
    $a space-concat= 'word2';     # RESULT: «'word1 word2'»

Although not strictly operators, methods can be used in the same fashion.

    my Real $a = 1/2;
    $a = 3.14;
    $a .= round;      # RESULT: «3»

=head1 Negated Relational Operators
X<|! (negation meta operator)>X<|!==>X<|!eq>

The result of a relational operator returning C<Bool> can be negated by
prefixing with C<!>. To avoid visual confusion with the C<!!> operator,
you may not modify any operator already beginning with C<!>.

There are shortcuts for C<!==> and C<!eq>, namely C<!=> and C<ne>.

    my $a = True;
    say so $a != True;    # OUTPUT: «False␤»
    my $i = 10;

    my $release = Date.new(:2015year, :12month, :24day);
    my $today = Date.today;
    say so $release !before $today;     # OUTPUT: «False␤»

=head1 Reversed Operators
X<|R,reverse meta operator>

Any infix operator may be called with its two arguments reversed by prefixing
with C<R>. Associativity of operands is reversed as well.

    say 4 R/ 12;        # OUTPUT: «3␤»
    say [R/] 2, 4, 16;  # OUTPUT: «2␤»

=head1 X<<<Hyper Operators|hyper,<<;hyper,>>;hyper,«;hyper,»>>>

Hyper Operators include C<«> and C<»>, with their ASCII variants C«<<»
and C«>>».

Hyper operators apply a given operator enclosed by C<«> and C<»> to one or two
lists, returning the resulting list. The pointy part of C<«> or C<»> has to
point to the shorter list. A list with just one element is fine too. If one of
the lists is shorter than the other, the operator will cycle over the shorter
list until all elements of the longer list are processed.

    say (1, 2, 3) »*» 2;          # OUTPUT: «(2 4 6)␤»
    say (1, 2, 3, 4) »~» <a b>;   # OUTPUT: «(1a 2b 3a 4b)␤»
    say (1, 2, 3) »+« (4, 5, 6);  # OUTPUT: «(5 7 9)␤»

Assignment meta operators can be hyped.

    my @a = 1, 2, 3;
    say @a »+=» 1;    # OUTPUT: «[2 3 4]␤»

Hyper forms of unary operators have the pointy bit point to the operator and
the blunt end at the list to be operated on.

    my @wisdom = True, False, True;
    say !« @wisdom;     # OUTPUT: «[False True False]␤»

    my @a = 1, 2, 3;
    @a»++;              # OUTPUT: «(2, 3, 4)␤»

Hyper operators are defined recursively on nested arrays.

    say -« [[1, 2], 3]; # OUTPUT: «[[-1 -2] -3]␤»

Also, methods can be called in an out of order, concurrent fashion. The resulting
list is in order. Note that all hyper operators are candidates for
autothreading and will cause tears if the methods have side effects. The
optimizer has full reign over hyper operators, which is the reason that they
cannot be defined by the user.

    class CarefulClass { method take-care {} }
    my CarefulClass @objs;
    my @results = @objs».take-care();

    my @slops;        # May Contain Nuts
    @slops».?this-method-may-not-exist();

Hyper operators can work with hashes. The pointy direction indicates if missing
keys are to be ignored in the resulting hash. The enclosed operator operates on
all values that have keys in both hashes.

=begin table
%foo «+» %bar;       intersection of keys

%foo »+« %bar;       union of keys

%outer »+» %inner;   only keys of %inner that exist in %outer will occur in the result
=end table

    my %outer = 1, 2, 3 Z=> <a b c>;
    my %inner = 1, 2 Z=> <x z>;
    say %outer «~» %inner;          # OUTPUT: «{"1" => "ax", "2" => "bz"}␤»

Hyper operators can take user defined operators as their operator argument.

    sub pretty-file-site (Int $size --> Str) {
        # rounding version of infix:</>(Int, Int)
        sub infix:<r/>(Int \i1, Int \i2) {
            round(i1 / i2, 0.1)
        }

        # we build a vector of fractions of $size and zip that with the fitting prefix
        for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)
                  Z      <EB     PB     TB     GB     MB     KB> -> [\v,\suffix] {
            # starting with the biggest suffix, we take the first that is 0.5 of that suffix or bigger
            return v ~ ' ' ~ suffix if v > 0.4
        }
        # this be smaller or equal then 0.4 KB
        return $size.Str;
    }

    for 60, 50, 40, 30, 20, 10 -> $test {
        my &a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };
        print pretty-file-site(a.Int) xx 2, ' ';
    }

    # OUTPUT: «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB␤»

Whether hyperoperators descend into child lists depends on the
L<nodality|/language/typesystem#trait_is_nodal> of the inner operator of a
chain. For the hyper method call operator (».), the nodality of the target
method is significant.

    say (<a b>, <c d e>)».elems;        # OUTPUT: «(2 3)␤»
    say (<a b>, <c d e>)».&{ .elems };  # OUTPUT: «((1 1) (1 1 1))␤»

You can chain hyper operators to destructure a List of Lists.

    my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));
    my $p = (2, 3);
    say $neighbors »>>+<<» ($p, *);   # OUTPUT: «((1 3) (2 2) (2 4) (3 3))␤»

=head1 Reduction Operators
X<|[] (reduction meta operators)>X<|[+] (reduction meta operators)>

The reduction metaoperator, C<[ ]>, reduces a list with the given infix
operator. It gives the same result as the L<reduce> routine - see there for
details.

    # These two are equivalent:
    say [+] 1, 2, 3;                # OUTPUT: «6␤»
    say reduce &infix:<+>, 1, 2, 3; # OUTPUT: «6␤»

No whitespace is allowed between the brackets and the operator. To wrap a
function instead of an operator, provide an additional layer of brackets:

    sub plus { $^a + $^b };
    say [[&plus]] 1, 2, 3;          # OUTPUT: «6␤»

The argument list is iterated without flattening. This means that you can pass
a nested list to the reducing form of a list infix operator:

    say [X~] (1, 2), <a b>;         # OUTPUT: «1, 2 X~ <a b>␤»

By default, only the final result of the reduction is returned. Prefix the
wrapped operator with a C<\>, to return a lazy list of all intermediate values
instead. This is called a "triangular reduce".
If the non-meta part contains a C<\> already,
quote it with C<[]> (e.g. C<[\[\x]]>).

    my @n = [\~] 1..*;
    say @n[^5];         # OUTPUT: «(1 12 123 1234 12345)␤»

=head1 Cross Operators
X<|X (cross meta operator)>

The cross metaoperator, C<X>, will apply a given infix operator in order of
cross product to all lists, such that the rightmost operator varies most
quickly.

    1..3 X~ <a b> # RESULT: «<1a, 1b, 2a, 2b, 3a, 3b>␤»

=head1 Zip Operators
X<|Z (zip meta operator)>

The zip metaoperator (which is not the same thing as L<Z|#infix_Z>) will
apply a given infix operator to pairs taken one left, one right, from its
arguments. The resulting list is returned.

    my @l = <a b c> Z~ 1, 2, 3;     # RESULT: «[a1 b2 c3]␤»

If one of the operands runs out of elements prematurely, the zip operator will
stop. An infinite list can be used to repeat elements. A list with a final
element of C<*> will repeat its 2nd last element indefinitely.

    my @l = <a b c d> Z~ ':' xx *;  # RESULT: «<a: b: c: d:>»
       @l = <a b c d> Z~ 1, 2, *;   # RESULT: «<a1 b2 c2 d2>»

If an infix operator is not given, C<,> (comma operator) will be used by default:

    my @l = 1 Z 2;  # RESULT: «[(1 2)]»

=head1 Sequential Operators
X<|S,sequential meta operator>

The sequential metaoperator, C<S>, will suppress any concurrency or reordering
done by the optimizer. Most simple infix operators are supported.

    say so 1 S& 2 S& 3;  # OUTPUT: «True␤»

=head1 Nesting of Meta Operators

To avoid ambiguity when chaining meta operators, use square brackets to help the
compiler understand you.

    my @a = 1, 2, 3;
    my @b = 5, 6, 7;
    @a X[+=] @b;
    say @a;         # OUTPUT: «[19 20 21]␤»

=head1 Z<>Term Precedence

=head2 term C«< >»

The X<quote-words|qw;quote-words> construct breaks up the contents on whitespace and returns
a L<List|/type/List> of the words. If a word
looks like a number literal or a C<Pair> literal, it's converted to the
appropriate number.

    say <a b c>[1];   # OUTPUT: «b␤»

=head2 term C«( )»

The X<grouping operator>.

An empty group C<()> creates an L<empty list|/type/List#index-entry-()_empty_list>.
Parentheses around non-empty expressions simply structure the expression, but do
not have additional semantics.

In an argument list, putting parenthesis around an argument prevents it from
being interpreted as a named argument.

    multi sub p(:$a!) { say 'named'      }
    multi sub p($a)   { say 'positional' }
    p a => 1;           # OUTPUT: «named␤»
    p (a => 1);         # OUTPUT: «positional␤»

=head2 term C«{ }»

L<Block> or L<Hash> constructor.X<|block constructor;hash constructor>

If the content is empty, or contains a single list that starts with a L<Pair> literal or
C<%>-sigiled variable, and the L«C<$_> variable|/syntax/$_» or placeholder parameters are
not used, the constructor returns a L<Hash>. Otherwise it constructs a L<Block>.

To force construction of a L<Block>, follow the opening brace with a semicolon.
To always ensure you end up with a L<Hash>, you can use C<%( )> coercer or L<hash> routine instead:

    {}.^name.say;        # OUTPUT: «Hash␤»
    {;}.^name.say;       # OUTPUT: «Block␤»

    {:$_}.^name.say;     # OUTPUT: «Block␤»
    %(:$_).^name.say;    # OUTPUT: «Hash␤»
    hash(:$_).^name.say; # OUTPUT: «Hash␤»

=head2 circumfix C«[ ]»

The X<L<Array> constructor> returns an itemized L<Array> that does not flatten
in list context.

=head1 Method Postfix Precedence

=head2 postcircumfix C«[ ]»

=begin code :skip-test
sub postcircumfix:<[ ]>(@container, **@index,
                        :$k, :$v, :$kv, :$p, :$exists, :$delete)
=end code

Universal interface for positional access to zero or more elements of a
@container, a.k.a. "X<array indexing operator|array indexing operator;array subscript operator>".

    my @alphabet = 'a' .. 'z';
    say @alphabet[0];                   # OUTPUT: «a␤»
    say @alphabet[1];                   # OUTPUT: «b␤»
    say @alphabet[*-1];                 # OUTPUT: «z␤»
    say @alphabet[100]:exists;          # OUTPUT: «False␤»
    say @alphabet[15, 4, 17, 11].join;  # OUTPUT: «perl␤»
    say @alphabet[23 .. *].perl;        # OUTPUT: «("x", "y", "z")␤»

    @alphabet[1, 2] = "B", "C";
    say @alphabet[0..3].perl            # OUTPUT: «("a", "B", "C", "d")␤»

See L<Subscripts|/language/subscripts>, for a more detailed explanation of this
operator's behavior and for how to implement support for it in custom types.

=head2 postcircumfix C«{ }»

=begin code :skip-test
sub postcircumfix:<{ }>(%container, **@key,
                        :$k, :$v, :$kv, :$p, :$exists, :$delete)
=end code

Universal interface for associative access to zero or more elements of a
%container, a.k.a. "X<hash indexing operator|hash indexing operator;hash subscript operator>".

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    say %color{"banana"};                 # OUTPUT: «yellow␤»
    say %color{"cherry", "kiwi"}.perl;    # OUTPUT: «("red", "green")␤»
    say %color{"strawberry"}:exists;      # OUTPUT: «False␤»

    %color{"banana", "lime"} = "yellowish", "green";
    %color{"cherry"}:delete;
    say %color;             # OUTPUT: «banana => yellowish, kiwi => green, lime => green␤»

See L«C«postcircumfix < >»|/routine/< >#(Operators)_postcircumfix_<_>» and
L<C<postcircumfix « »>|/routine/« »#(Operators)_postcircumfix_«_»> for convenient
shortcuts, and L<Subscripts|/language/subscripts> for a more detailed
explanation of this operator's behavior and how to implement support for it
in custom types.

=head2 postcircumfix C«< >»

Shortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}> that quotes
its argument using the same rules as the L«quote-words operator|
/routine/< >#circumfix_<_>» of the same name.

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    say %color<banana>;               # OUTPUT: «yellow␤»
    say %color<cherry kiwi>.perl;     # OUTPUT: «("red", "green")␤»
    say %color<strawberry>:exists;    # OUTPUT: «False␤»

Technically, not a real operator; it's syntactic sugar that's turned into the
C<{ }> postcircumfix operator at compile-time.

=head2 postcircumfix C<« »>

Shortcut for L<C<postcircumfix { }>|/routine/{ }#(Operators)_postcircumfix_{_}> that quotes
its argument using the same rules as the L<interpolating quote-words operator|
/routine/« »#circumfix_«_»> of the same name.

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    my $fruit = "kiwi";
    say %color«cherry "$fruit"».perl;   # OUTPUT: «("red", "green")␤»

Technically, not a real operator; it's syntactic sugar that's turned into the
C<{ }> postcircumfix operator at compile-time.

=head2 postcircumfix C«( )»

The X<call operator> treats the invocant as a L<Callable> and invokes it,
using the expression between the parentheses as arguments.

Note that an identifier followed by a pair of parentheses is always parsed as a
subroutine call.

If you want your objects to respond to the call operator,
implement a C<method CALL-ME>.

=head2 postfix C«.»

The operator for calling one method, C<$invocant.method>.X<|method call>

Technically, not a real operator; it's syntax special-cased in the compiler.

X«|postfix .&»
=head2 postfix C«.&»

The operator to call a subroutine (with at least one positional argument), such
as a method. The invocant will be bound to the first positional argument.

Technically, not a real operator; it's syntax special-cased in the compiler.

    my sub f($invocant){ "The arg has a value of $invocant" }
    42.&f;
    # OUTPUT: «The arg has a value of 42␤»

    42.&(-> $invocant { "The arg has a value of $invocant" });
    # OUTPUT: «The arg has a value of 42␤»

=head2 postfix C«.=»

A X<mutating method call>. C<$invocant.=method> desugars to
C<$invocant = $invocant.method>, similar to L<C<=>>.

Technically, not a real operator; it's syntax special-cased in the compiler.

X«|postfix .^»
=head2 postfix C«.^»

A X<meta-method call>. C<$invocant.^method> calls C<method> on C<$invocant>'s
metaclass. It desugars to C<$invocant.HOW.method($invocant, ...)>. See
L<HOW|/language/mop#index-entry-syntax_HOW-HOW> for more information.

Technically, not a real operator; it's syntax special-cased in the compiler.

X«|postfix .?»
=head2 postfix C«.?»

X<Safe call operator>. C<$invocant.?method> calls method C<method> on
C<$invocant> if it has a method of such name. Otherwise it returns L<Nil>.

Technically, not a real operator; it's syntax special-cased in the compiler.

X«|postfix .+»
=head2 postfix C«.+»

C<$invocant.+method> calls all methods called C<method> from C<$invocant>,
and returns a L<List> of the results. Dies if no such method was found.

Technically, not a real operator; it's syntax special-cased in the compiler.

X«|postfix .*»
=head2 postfix C«.*»

C<$invocant.*method> calls all methods called C<method> from C<$invocant>,
and returns a L<List> of the results. If no such method was found, an empty
L<List> is returned.

Technically, not a real operator; it's syntax special-cased in the compiler.

X<|postfix ».>X«|postfix >>.»
=head2 postfix C<».> / postfix C«>>.»

X<Hyper method call operator>. Will call a method on all elements of a C<List> out of order and return the list of return values in order.

    my @a = <a b c>;
    my @b = @a».ord;                  # OUTPUT: «[97, 98, 99]␤»
    sub foo(Str:D $c){ $c.ord * 2 };  # The first parameter of a method is the invocant.
    say @a».&foo;                     # So we can pretend to have a method call with a sub that got a good first positional argument.
    say @a».&{ .ord};                 # Blocks have an implicit positional arguments that lands in $_. The latter can be omitted for method calls.

Take care to avoid a
L<common mistake|/language/traps#Using_»_and_map_interchangeably> of expecting
side-effects to occur in order. The following C<say> is B<not>
guaranteed to produce the output in order:

    =begin code :skip-test
    @a».say;  # WRONG! Could produce a␤b␤c␤ or c␤b␤a␤ or any other order
    =end code

=head2 postfix C<.postfix> / C<.postcircumfix>
X<|.( )>X<|.[ ]>X<|.{ }>

In most cases, a dot may be placed before a postfix or postcircumfix:

    my @a;
    @a[1, 2, 3];
    @a.[1, 2, 3]; # Same

This can be useful for visual clarity or brevity. For example, if an object's
attribute is a function, putting a pair of parentheses after the attribute name
will become part of the method call. So, either two pairs of parentheses must be
used or a dot has to come before the parentheses to separate it from the method
call.

    class Operation {
        has $.symbol;
        has &.function;
    }
    my $addition = Operation.new(:symbol<+>, :function{ $^a + $^b });
    say $addition.function()(1, 2);   # OUTPUT: «3␤»
    # OR
    say $addition.function.(1, 2);    # OUTPUT: «3␤»

If the postfix is an identifier, however, it will be interpreted as a normal
method call.

=begin code
1.i # No such method 'i' for invocant of type 'Int'
=end code

Technically, not a real operator; it's syntax special-cased in the compiler.
X<|postfix call>

=head2 postfix C«.:<prefix>»

A prefix can be called like a method using colonpair notation. For example:

    my $a = 1;
    say ++$a;       # OUTPUT: «2␤»
    say $a.:<++>;   # OUTPUT: «3␤»

Technically, not a real operator; it's syntax special-cased in the compiler.
X<|prefix call>

=head2 postfix C«.::»

A X<class-qualified method call>, used to call a method as defined in a parent
class or role, even after it has been redefined in the child class.

    class Bar {
        method baz { 42 }
    }
    class Foo is Bar {
        method baz { "nope" }
    }
    say Foo.Bar::baz;       # OUTPUT: «42␤»

=head1 Autoincrement Precedence

=head2 prefix X<C«++»|++>

    multi sub prefix:<++>($x is rw) is assoc<non>

Increments its argument by one and returns the updated value.X<|increment operator>

    my $x = 3;
    say ++$x;   # OUTPUT: «4␤»
    say $x;     # OUTPUT: «4␤»

It works by calling the L<succ> method (for I<successor>) on its argument,
which gives custom types the freedom to implement their own increment
semantics.

=head2 prefix X<C«--»|-->

    multi sub prefix:<-->($x is rw) is assoc<non>

Decrements its argument by one and returns the updated value.X<|decrement operator>

    my $x = 3;
    say --$x;   # OUTPUT: «2␤»
    say $x;     # OUTPUT: «2␤»

It works by calling the L<pred> method (for I<predecessor>) on its argument,
which gives custom types the freedom to implement their own decrement
semantics.


=head2 postfix X<C«++»|++>

    multi sub postfix:<++>($x is rw) is assoc<non>

Increments its argument by one and returns the original value.X<|increment operator>

    my $x = 3;
    say $x++;   # OUTPUT: «3␤»
    say $x;     # OUTPUT: «4␤»

It works by calling the L<succ> method (for I<successor>) on its argument,
which gives custom types the freedom to implement their own increment
semantics.

Note that this does not necessarily return its argument; e.g., for
undefined values, it returns 0:

    my $x;
    say $x++;   # OUTPUT: «0␤»
    say $x;     # OUTPUT: «1␤»

Increment on L<Str|/type/Str> will increment the number part of a string and
assign the resulting string to the container. A C<is rw>-container is required.

    my $filename = "somefile-001.txt";
    say $filename++ for 1..3;
    # OUTPUT: «somefile-001.txt␤somefile-002.txt␤somefile-003.txt␤»

=head2 postfix C«--»

    multi sub postfix:<-->($x is rw) is assoc<non>

Decrements its argument by one and returns the original value.X<|decrement operator>

    my $x = 3;
    say $x--;   # OUTPUT: «3␤»
    say $x;     # OUTPUT: «2␤»

It works by calling the L<pred> method (for I<predecessor>) on its argument,
which gives custom types the freedom to implement their own decrement
semantics.

Note that this does not necessarily return its argument;e.g., for
undefined values, it returns 0:

    my $x;
    say $x--;   # OUTPUT: «0␤»
    say $x;     # OUTPUT: «-1␤»

Decrement on L<Str|/type/Str> will decrement the number part of a string and
assign the resulting string to the container. A C<is rw>-container is required.
Crossing 0 is prohibited and throws C<X::AdHoc>.

    my $filename = "somefile-003.txt";
    say $filename-- for 1..3;
    # OUTPUT: «somefile-003.txt␤somefile-002.txt␤somefile-001.txt␤»

=head1 Exponentiation Precedence

=head2 infix C«**»

    multi sub infix:<**>(Any, Any --> Numeric:D) is assoc<right>

The X<exponentiation operator> coerces both arguments to L<Numeric>
and calculates the left-hand-side raised to the power of the right-hand side.

If the right-hand side is a non-negative integer and the left-hand side
is an arbitrary precision type (L<Int>, L<FatRat>), then the calculation
is carried out without loss of precision.

=head1 Symbolic Unary Precedence

=head2 prefix C«?»

    multi sub prefix:<?>(Mu --> Bool:D)

X<Boolean context operator>.

Coerces the argument to L<Bool> by calling the C<Bool> method on it.
Note that this collapses L<Junction>s.

=head2 prefix C«!»

    multi sub prefix:<!>(Mu --> Bool:D)

X<Negated boolean context operator>.

Coerces the argument to L<Bool> by calling the C<Bool> method on it,
and returns the negation of the result.
Note that this collapses L<Junction>s.

=head2 prefix C«+»

    multi sub prefix:<+>(Any --> Numeric:D)

X<Numeric context operator>.

Coerces the argument to L<Numeric> by calling the C<Numeric> method on it.

=head2 prefix C«-»

    multi sub prefix:<->(Any --> Numeric:D)

X<Negative numeric context operator>.

Coerces the argument to L<Numeric> by calling the C<Numeric> method on it,
and then negates the result.

=head2 prefix C«~»

    multi sub prefix:<~>(Any --> Str:D)

X<String context operator>.

Coerces the argument to L<Str> by calling the L<Str|/type/List#method_Str> method on it.

=head2 prefix C«|»

Flattens objects of type L<Capture>, L<Pair>, L<List>, L<Map> and L<Hash>
into an argument list.

Outside of argument lists, it returns a L<Slip|/type/Slip>, which makes it
flatten into the outer list. Inside L<argument list|/language/list#Argument_List_(Capture)_Context> L<C<Positional>s|/type/Positional> are turned
into positional arguments and L<C<Associative>s|/type/Associative> are turned into named arguments.

=head2 prefix C«||»

TODO

=head2 prefix C«+^»

    multi sub prefix:<+^>(Any --> Int:D)

X<Integer bitwise negation operator>.

Coerces the argument to L<Int> and does a bitwise negation on the result,
assuming L<two's complement|https://en.wikipedia.org/wiki/Two%27s_complement>.

=head2 prefix C«~^»

Coerces the argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then flips each bit in that buffer.

Please note that this has not yet been implemented.

=head2 prefix C«?^»

    multi sub prefix:<?^>(Mu --> Bool:D)

X<Boolean bitwise negation operator>.

Coerces the argument to L<Bool> and then does a bit flip, which makes it the
same as C<< prefix:<!> >>.

=head2 prefix C«^»

    multi sub prefix:<^>(Any --> Range:D)

I<upto> operator.X<|upto operator>

Coerces the argument to L<Numeric>, and generates a range from 0 up to (but
excluding) the argument.

    say ^5;         # OUTPUT: «0..^5␤»
    for ^5 { }      # 5 iterations

=head1 Dotty Infix Precedence

These operators are like their Method Postfix counterparts, but require
surrounding whitespace (before and/or after) to distinguish them.

=head2 infix C«.=»

Calls the right-side method on the value in the left-side container,
replacing the resulting value in the left-side container.

In most cases, this behaves identically to the postfix mutator, but the
precedence is lower:

=for code :skip-test
    my $a = -5
    say ++$a.=abs
    # OUTPUT: «6␤»
    say ++$a .= abs
    # OUTPUT: «Cannot modify an immutable Int␤
    #           in block <unit> at <tmp> line 1␤␤»

=head2 infix C«.»

Calls the following method (whose name must be alphabetic) on the left-side
invocant.

Note that the infix form of the operator has a slightly lower precedence
than postfix C<.meth>.

    say -5.abs;      # like: -(5.abs)
    # OUTPUT: «-5␤»
    say -5 . abs;    # like: (-5) . abs
    # OUTPUT: «5␤»
    say -5 .abs;     # following whitespace is optional
    # OUTPUT: «5␤»

=head1 Multiplicative Precedence

=head2 infix C«*»

    multi sub infix:<*>(Any, Any --> Numeric:D)

X<Multiplication operator>.

Coerces both arguments to L<Numeric> and multiplies them. The result
is of the wider type. See L<Numeric> for details.

=head2 infix C«/»

    multi sub infix:</>(Any, Any --> Numeric:D)

X<Division operator>.

Coerces both argument to L<Numeric> and divides the left through the right
number. Division of L<Int> values returns L<Rat>, otherwise the "wider type"
rule described in L<Numeric> holds.

=head2 infix C«div»

    multi sub infix:<div>(Int:D, Int:D --> Int:D)

X<Integer division operator>. Rounds down.

=head2 infix C«%»

    multi sub infix:<%>($x, $y --> Numeric:D)

X<Modulo operator>. Coerces to L<Numeric> first.

Generally the following identity holds:

    my ($x, $y) = 1,2;
    $x % $y == $x - floor($x / $y) * $y

=head2 infix C«%%»

    multi sub infix:<%%>($a, $b --> Bool:D)

X<Divisibility operator>. Returns C<True> if C<$a %  $b == 0>.

=head2 infix C«mod»

    multi sub infix:<mod>(Int:D $a, Int:D $b --> Int:D)

X<Integer modulo operator>. Returns the remainder of an integer modulo operation.

=head2 infix C«+&»

    multi sub infix:<+&>($a, $b --> Int:D)

Numeric bitwise I<AND> operator. Coerces both arguments to L<Int> and does a bitwise
I<AND> operation assuming two's complement.X<|Numeric bitwise AND operator>

=head2 infix C«+<»

    multi sub infix:<< +< >>($a, $b --> Int:D)

Integer bit shift to the left.X<|integer bit shift operator,left>

=head2 infix C«+>»

    multi sub infix:<< +> >>($a, $b --> Int:D)

Integer bit shift to the right.X<|integer bit shift operator,right>

=head2 infix C«~&»

Coerces each argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then performs a numeric bitwise AND on corresponding integers of the two buffers, padding the
shorter buffer with zeroes.

=head2 infix C«~<»

Coerces the left argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then performs a numeric bitwise left shift on the bits of the buffer.

Please note that this has not yet been implemented.

=head2 infix C«~>»

Coerces the left argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then performs a numeric bitwise right shift on the bits of the buffer.

Please note that this has not yet been implemented.

=head2 infix C«gcd»

    multi sub infix:<gcd>($a, $b --> Int:D)

Coerces both arguments to L<Int> and returns the greatest common divisor.X<|greatest common divisor operator>

=head2 infix C«lcm»

    multi sub infix:<lcm>($a, $b --> Int:D)

Coerces both arguments to L<Int> and returns the least common multiple; that is,
the smallest integer that is evenly divisible by both arguments.X<|least common multiple operator>

=head1 Additive Precedence

=head2 infix C«+»

    multi sub infix:<+>($a, $b --> Numeric:D)

X<Addition operator>.

Coerces both arguments to L<Numeric> and adds them.

=head2 infix C«-»

    multi sub infix:<->($a, $b --> Numeric:D)

X<Subtraction operator>.

Coerces both arguments to L<Numeric> and subtracts the second from the
first.

=head2 infix C«+|»

    multi sub infix:<+|>($a, $b --> Int:D)

X<Integer bitwise OR operator>.

Coerces both arguments to L<Int> and does a bitwise I<OR> (inclusive OR)
operation.

=head2 infix C«+^»

    multi sub infix:<+^>($a, $b --> Int:D)

X<Integer bitwise XOR operator>.

Coerces both arguments to L<Int> and does a bitwise I<XOR> (exclusive OR)
operation.

=head2 infix C«~|»

Coerces each argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then performs a numeric bitwise OR on corresponding integers of the two buffers, padding the
shorter buffer with zeroes.

=head2 infix C«~^»

Coerces each argument to a non-variable-encoding string buffer type (e.g. C<buf8>, C<buf16>, C<buf32>)
and then performs a numeric bitwise XOR on corresponding integers of the two buffers, padding the
shorter buffer with zeroes.

=head2 infix C«?|»

    multi sub infix:<?|>($a, $b --> Bool:D)

X<Boolean logical OR operator>.

Coerces both arguments to L<Bool> and does a logical I<OR> (inclusive OR)
operation.

=head1 Replication Precedence

=head2 infix C«x»

    sub infix:<x>($a, $b --> Str:D)

X<String repetition operator>.

Repeats the string C<$a> C<$b> times, if necessary coercing C<$a> to L«C<Str>|/type/Str»
and C<$b> L«C<Int>|/type/Int». Returns an empty string if C<< $b <= 0 >>.

    say 'ab' x 3;           # OUTPUT: «ababab␤»
    say 42 x 3;             # OUTPUT: «424242␤»

    my $a = 'a'.IO;
    my $b = 3.5;
    say $a x $b;            # OUTPUT: «aaa␤»

=head2 infix C«xx»

    multi sub infix:<xx>($a, $b --> List:D)

X<List repetition operator>.

Returns a list of C<$a> repeated and evaluated C<$b> times (C<$b> is coerced
to L<Int>). If C<< $b <= 0 >>, the empty list is returned.

The left-hand side is evaluated for each repetition, so

    say [1, 2] xx 5;
    # OUTPUT: «([1 2] [1 2] [1 2] [1 2] [1 2])␤»

returns five distinct arrays (but with the same content each time), and

    rand xx 3

returns three pseudo random numbers that are determined independently.

The right-hand side can be C<*>, in which case a lazy, infinite list
is returned.

=head1 Concatenation

=head2 infix C«~»

    multi sub infix:<~>(Any,   Any)
    multi sub infix:<~>(Str:D, Str:D)
    multi sub infix:<~>(Buf:D, Buf:D)

X<String concatenation operator>.

Coerces both arguments to L<Str> and concatenates them. If both arguments are
L<Buf|/type/Buf>, a combined buffer is returned.

    say 'ab' ~ 'c';     # OUTPUT: «abc␤»

=head2 infix C«∘»

    multi sub infix:<∘>()
    multi sub infix:<∘>(&f)
    multi sub infix:<∘>(&f, &g --> Block:D)

X<Function combinator operator>

The function composition operator C«infix:<∘>» or C«infix:<o>» combines two
functions, so that the left function is called with the return value of the
right function. If the L«C<.count>|/routine/count» of the left function is
greater than 1, the return value of the right function will be
L<slipped|/type/Slip> into the left function.

Both C<.count> and C<.arity> of the RHS will be maintained.

    sub f($p){ say 'f'; $p / 2 }
    sub g($p){ say 'g'; $p * 2 }

    my &composed = &f ∘ &g;
    say composed 2; # OUTPUT: «g␤f␤2␤»
    # equivalent to:
    say 2.&g.&f;
    # or to:
    say f g 2;

    =begin code
    sub f($a, $b, $c) { [~] $c, $b, $a }
    sub g($str){ $str.comb }
    my &composed = &f ∘ &g;
    say composed 'abc'; # OUTPUT: «cba␤»
    # equivalent to:
    say f |g 'abc';
    =end code

=head1 Junctive AND (all) Precedence

=head2 infix C«&»

    multi sub infix:<&>($a, $b --> Junction:D) is assoc<list>

X<All junction operator>.

Creates an I<all> L<Junction> from its arguments. See L<Junction> for more
details.

=head1 Junctive OR (any) Precedence

=head2 infix C«|»

    multi sub infix:<|>($a, $b --> Junction:D) is assoc<list>

X<Any junction operator>.

Creates an I<any> L<Junction> from its arguments. See L<Junction> for more
details.

=head2 infix C«^»

    multi sub infix:<^>($a, $b --> Junction:D) is assoc<list>

X<One junction operator>.

Creates a I<one> L<Junction> from its arguments. See L<Junction> for more
details.

=head1 Named Unary Precedence

=head2 prefix C«temp»

    sub prefix:<temp>(Mu $a is rw)

"temporizes" the variable passed as the argument. The variable begins
with the same value as it had in the outer scope, but can be assigned
new values in this scope. Upon exiting the scope, the variable will be
restored to its original value.

    my $a = "three";
    say $a; # OUTPUT: «three␤»
    {
        temp $a;
        say $a; # OUTPUT: «three␤»
        $a = "four";
        say $a; # OUTPUT: «four␤»
    }
    say $a; # OUTPUT: «three␤»

You can also assign immediately as part of the call to temp:

    =begin code :skip-test
    temp $a = "five";
    =end code

Be warned the C<temp> effects get removed once the block is left. If
you were to access the value from, say, within a L<Promise> after
the C<temp> was undone, you'd get the original value, not the C<temp> one:

    =begin code
    my $v = "original";
    {
        temp $v = "new one";
        start {
            say "[PROMISE] Value before block is left: `$v`";
            sleep 1;
            say "[PROMISE] Block was left while we slept; value is now `$v`";
        }
        sleep ½;
        say "About to leave the block; value is `$v`";
    }
    say "Left the block; value is now `$v`";
    sleep 2;

    # OUTPUT:
    # [PROMISE] Value before block is left: `new one`
    # About to leave the block; value is `new one`
    # Left the block; value is now `original`
    # [PROMISE] Block was left while we slept; value is now `original`
    =end code


=head2 prefix C«let»

    sub prefix:<let>(Mu $a is rw)

Restores the previous value if the block exits unsuccessfully. A
successful exit means the block returned a defined value or a list.

    my $answer = 42;

    {
        let $answer = 84;
        die if not Bool.pick;
        CATCH {
            default { say "it's been reset :(" }
        }
        say "we made it 84 sticks!";
    }

    say $answer;

In the above case, if the C<Bool.pick> returns true, the answer will
stay as 84 because the block returns a defined value (C<say> returns
true). Otherwise the C<die> statement will cause the block to exit
unsuccessfully, resetting the answer to 42.

=comment this is duplicated in variables.pod

=head1 Nonchaining Binary Precedence

=head2 infix C«does»

    sub infix:<does>(Mu $obj, Mu $role) is assoc<non>

Mixes C<$role> into C<$obj> at run time. Requires C<$obj> to be mutable.

Similar to L<but> operator, the C<$role> can instead be an instantiated object,
in which case, the operator will create a role for you automatically.
The role will contain a single method named the same as C<$obj.^name>
and that returns C<$obj>:

    my $o = class { method Str { "original" } }.new;
    put $o;            # OUTPUT: «original␤»
    $o does "modded";
    put $o;            # OUTPUT: «modded␤»

If methods of the same name are present already, the last mixed in role takes
precedence.

=head2 infix C«but»

    multi sub infix:<but>(Mu $obj1, Mu   $role) is assoc<non>
    multi sub infix:<but>(Mu $obj1, Mu:D $obj2) is assoc<non>

Creates a copy of C<$obj> with C<$role> mixed in. Since C<$obj> is not
modified, C<but> can be used to created immutable values with mixins.

Instead of a role, you can provide an instantiated object. In this case,
the operator will create a role for you automatically. The role will contain
a single method named the same as C<$obj.^name> and that returns C<$obj>:

    =begin code
    say 42 but 'forty two'; # OUTPUT: «forty two␤»

    my $s = 12 but class Warbles { method hi { 'hello' } }.new;
    say $s.Warbles.hi;    # OUTPUT: «hello␤»
    say $s + 42;          # OUTPUT: «54␤»
    =end code

If methods of the same name are present already, the last mixed in role takes
precedence. A list of methods can be provided in parentheses separated by
comma. In this case conflicts will be reported at runtime.

=head2 infix C«cmp»

    multi sub infix:<cmp>(Any,       Any)
    multi sub infix:<cmp>(Real:D,    Real:D)
    multi sub infix:<cmp>(Str:D,     Str:D)
    multi sub infix:<cmp>(Version:D, Version:D)

X<Generic, "smart" three-way comparator>.

Compares strings with string semantics, numbers
with number semantics, L<Pair> objects first by key and then by value etc.

if C<$a eqv $b>, then C<$a cmp $b> always returns C<Order::Same>.

    say (a => 3) cmp (a => 4);   # OUTPUT: «Less␤»
    say 4        cmp 4.0;        # OUTPUT: «Same␤»
    say 'b'      cmp 'a';        # OUTPUT: «More␤»

=head2 infix C«leg»

    multi sub infix:<leg>(Any,   Any)
    multi sub infix:<leg>(Str:D, Str:D)

X<String three-way comparator>. Short for I<less, equal or greater?>.

Coerces both arguments to L<Str> and then does a lexicographic comparison.

    say 'a' leg 'b';       # OUTPUT: «Less␤»
    say 'a' leg 'a';       # OUTPUT: «Same␤»
    say 'b' leg 'a';       # OUTPUT: «More␤»

=head2 infix C«<=>»

    multi sub infix:«<=>»($a, $b --> Order:D) is assoc<non>

X<Numeric three-way comparator>.X<|spaceship operator>

Coerces both arguments to L<Real> and then does a numeric comparison.

=head2 infix C«..»

    multi sub infix:<..>($a, $b --> Range:D) is assoc<non>

X<Range operator>

Constructs a L<Range> from the arguments.

=head2 infix C«..^»

    multi sub infix:<..^>($a, $b --> Range:D) is assoc<non>

X<Right-open range operator>.

Constructs a L<Range> from the arguments, excluding the end point.

=head2 infix C«^..»

    multi sub infix:<^..>($a, $b --> Range:D) is assoc<non>

X<Left-open range operator>.

Constructs a L<Range> from the arguments, excluding the start point.

=head2 infix C«^..^»

    multi sub infix:<^..^>($a, $b --> Range:D) is assoc<non>

X<Open range operator>

Constructs a L<Range> from the arguments, excluding both start and end point.

=head1 Chaining Binary Precedence

=head2 infix C«==»

    multi sub infix:<==>(Any, Any)
    multi sub infix:<==>(Int:D, Int:D)
    multi sub infix:<==>(Num:D, Num:D)
    multi sub infix:<==>(Rational:D, Rational:D)
    multi sub infix:<==>(Real:D, Real:D)
    multi sub infix:<==>(Complex:D, Complex:D)
    multi sub infix:<==>(Numeric:D, Numeric:D)

X<Numeric equality operator>.

Coerces both arguments to L<Numeric> (if necessary); returns C<True>
if they are equal.

=head2 infix C«!=»

    sub infix:<!=>(Mu, Mu --> Bool:D)

X<Numeric inequality operator>.

Coerces both arguments to L<Numeric> (if necessary); returns C<True> if they are
distinct.

Is an alias to C«!==».

=head2 infix C«≠»

Numeric inequality operator.

Equivalent to L«!=», at codepoint U+2260 (NOT EQUAL TO).

=head2 infix C«<»

    multi sub infix:«<»(Int:D, Int:D)
    multi sub infix:«<»(Num:D, Num:D)
    multi sub infix:«<»(Real:D, Real:D)

X<Numeric less than operator>.

Coerces both arguments to L<Real> (if necessary); returns C<True> if the first argument
is smaller than the second.

=head2 infix C«<=»

    multi sub infix:«<=»(Int:D, Int:D)
    multi sub infix:«<=»(Num:D, Num:D)
    multi sub infix:«<=»(Real:D, Real:D)

X<Numeric less than or equal to operator>.

Coerces both arguments to L<Real> (if necessary); returns C<True> if the first argument
is smaller than or equal to the second.

=head2 infix C«≤»

Numeric less than or equal to operator.

Equivalent to L«<=», at codepoint U+2264 (LESS-THAN OR EQUAL TO).

=head2 infix C«>»

    multi sub infix:«>»(Int:D, Int:D)
    multi sub infix:«>»(Num:D, Num:D)
    multi sub infix:«>»(Real:D, Real:D)

X<Numeric greater than operator>.

Coerces both arguments to L<Real> (if necessary); returns C<True> if the first argument
is larger than the second.

=head2 infix C«>=»

    multi sub infix:«>=»(Int:D, Int:D)
    multi sub infix:«>=»(Num:D, Num:D)
    multi sub infix:«>=»(Real:D, Real:D)

X<Numeric greater than or equal to operator>.

Coerces both arguments to L<Real> (if necessary); returns C<True> if
the first argument is larger than or equal to the second.

=head2 infix C«≥»

Numeric greater than or equal to operator.

Equivalent to L«>=», at codepoint U+2265 (GREATER-THAN OR EQUAL TO).

=head2 infix C«eq»

    multi sub infix:<eq>(Any,   Any)
    multi sub infix:<eq>(Str:D, Str:D)

X<String equality operator>.

Coerces both arguments to L<Str> (if necessary); returns C<True> if both
are equal.

Mnemonic: I<equal>

=head2 infix C«ne»

    multi sub infix:<ne>(Mu,    Mu)
    multi sub infix:<ne>(Str:D, Str:D)

X<String inequality operator>.

Coerces both arguments to L<Str> (if necessary); returns C<False> if both
are equal.

Mnemonic: I<not equal>

=head2 infix C«gt»

    multi sub infix:<gt>(Mu,    Mu)
    multi sub infix:<gt>(Str:D, Str:D)

X<String greater than operator>.

Coerces both arguments to L<Str> (if necessary); returns C<True> if
the first is larger than the second, as determined by lexicographic
comparison.

Mnemonic: I<greater than>

=head2 infix C«ge»

    multi sub infix:<ge>(Mu,    Mu)
    multi sub infix:<ge>(Str:D, Str:D)

X<String greater than or equal to operator>.

Coerces both arguments to L<Str> (if necessary); returns C<True> if
the first is equal to or larger than the second, as determined by lexicographic
comparison.

Mnemonic: I<greater or equal>

=head2 infix C«lt»

    multi sub infix:<lt>(Mu,    Mu)
    multi sub infix:<lt>(Str:D, Str:D)

X<String less than operator>.

Coerces both arguments to L<Str> (if necessary); returns C<True> if
the first is smaller than the second, as determined by lexicographic
comparison.

Mnemonic: I<less than>

=head2 infix C«le»

    multi sub infix:<le>(Mu,    Mu)
    multi sub infix:<le>(Str:D, Str:D)

X<String less than or equal to operator>.

Coerces both arguments to L<Str> (if necessary); returns C<True> if
the first is equal to or smaller than the second, as determined by lexicographic
comparison.

Mnemonic: I<less or equal>

=head2 infix C«before»

    multi sub infix:<before>(Any,       Any)
    multi sub infix:<before>(Real:D,    Real:D)
    multi sub infix:<before>(Str:D,     Str:D)
    multi sub infix:<before>(Version:D, Version:D)

Generic ordering, uses the same semantics as L<cmp|#infix cmp>.
Returns C<True> if the first argument is smaller than the second.

=head2 infix C«after»

    multi sub infix:<after>(Any,       Any)
    multi sub infix:<after>(Real:D,    Real:D)
    multi sub infix:<after>(Str:D,     Str:D)
    multi sub infix:<after>(Version:D, Version:D)

Generic ordering, uses the same semantics as L<cmp|#infix cmp>.
Returns C<True> if the first argument is larger than the second.

=head2 infix C«eqv»

    sub infix:<eqv>(Any, Any)

X<Equivalence operator>. Returns C<True> if the two arguments are structurally
the same, i.e. from the same type and (recursively) contain equivalent values.

    say [1, 2, 3] eqv [1, 2, 3];    # OUTPUT: «True␤»
    say Any eqv Any;                # OUTPUT: «True␤»
    say 1 eqv 2;                    # OUTPUT: «False␤»
    say 1 eqv 1.0;                  # OUTPUT: «False␤»

Lazy L«C<Iterables>|/type/Iterable» cannot be compared, as
they're assumed to be infinite. However, the operator will do its best and
return C<False> if the two lazy C<Iterables> are of different types or
if only one C<Iterable> is lazy.

    say (1…∞) eqv (1…∞).List; # Both lazy, but different types;   OUTPUT: «False␤»
    say (1…∞) eqv (1…3);      # Same types, but only one is lazy; OUTPUT: «False␤»
    (try say (1…∞) eqv (1…∞)) # Both lazy and of the same type. Cannot compare; throws.
        orelse say $!.^name;  # OUTPUT: «X::Cannot::Lazy␤»

The default C<eqv> operator even works with arbitrary objects. E.g., C<eqv>
will consider two instances of the same object as being structurally
equivalent:

    my class A {
        has $.a;
    }
    say A.new(a => 5) eqv A.new(a => 5);  # OUTPUT: «True␤»

Although the above example works as intended, the C<eqv> code might fall back
to a slower code path in order to do its job. One way to avoid this is to
implement an appropriate infix C<eqv> operator:

    my class A {
        has $.a;
    }
    multi infix:<eqv>(A $l, A $r) { $l.a eqv $r.a }
    say A.new(a => 5) eqv A.new(a => 5);            # OUTPUT: «True␤»

=head2 infix C«===»

    sub infix:<===>(Any, Any)

X<Value identity operator>. Returns C<True> if both arguments are the same object.

    my class A { };
    my $a = A.new;
    say $a === $a;              # OUTPUT: «True␤»
    say A.new === A.new;        # OUTPUT: «False␤»
    say A === A;                # OUTPUT: «True␤»

For value types, C<===> behaves like C<eqv>:

    say 'a' === 'a';            # OUTPUT: «True␤»
    say 'a' === 'b';            # OUTPUT: «False␤»

    # different types
    say 1 === 1.0;              # OUTPUT: «False␤»

C<===> uses the L<WHICH|/routine/WHICH> method to obtain the object identity, so all value
types must override method C<WHICH>.

=head2 infix C«=:=»

    multi sub infix:<=:=>(Mu \a, Mu \b)

X<Container identity operator>. Returns C<True> if both arguments are bound to the same
container. If it returns C<True>, it generally means that modifying one will
also modify the other.

    my ($a, $b) = (1, 3);
    say $a =:= $b;      # OUTPUT: «False␤»
    $b = 2;
    say $a;             # OUTPUT: «1␤»
    $b := $a;
    say $a =:= $b;      # OUTPUT: «True␤»
    $a = 5;
    say $b;             # OUTPUT: «5␤»

=head2 infix C«~~»

X<|smartmatch operator>
The X<smart-match operator>. Aliases the left-hand side to C<$_>, then evaluates
the right-hand side and calls C<.ACCEPTS($_)> on it. The semantics are left
to the type of the right-hand side operand.

Here is a partial list of some of the built-in smart-matching functionality. For
full details, see L<ACCEPTS|/routine/ACCEPTS> documentation
for the type on the right-hand side of the operator.

=begin table

    Right-hand side     Comparison semantics
    ===============     ====================
    Mu:U                type check
    Str                 string equality
    Numeric             numeric equality
    Regex               regex match
    Callable            boolean result of invocation
    Set/Bag             equal element values
    Any:D               object identity

=end table

=head2 infix C<=~=>

    multi sub infix:<=~=>(Any, Any)
    multi sub infix:<=~=>(Int:D, Int:D)
    multi sub infix:<=~=>(Num:D, Num:D)
    multi sub infix:<=~=>(Rational:D, Rational:D)
    multi sub infix:<=~=>(Real:D, Real:D)
    multi sub infix:<=~=>(Complex:D, Complex:D)
    multi sub infix:<=~=>(Numeric:D, Numeric:D)

The approximately-equal operator X<C<≅>|infix, ≅>, whose ASCII variant is
C<=~=>. Calculates the relative difference between the left-hand and right-hand
sides and returns C<True> if the difference is less than $*TOLERANCE
(which defaults to 1e-15). However, if either side is zero then it checks that
the absolute difference between the sides is less than $*TOLERANCE. Note that
this operator is not arithmetically symmetrical (doesn't do ± Δ):

    my $x = 1;
    say ($x + $*TOLERANCE) =~= $x;   # OUTPUT: «False␤»
    say ($x - $*TOLERANCE) =~= $x;   # OUTPUT: «True␤»

The tolerance is supposed to be modifiable via an adverb:

=comment RT #128210
=begin code :skip-test
my ($x, $y) = 42, 42.1;
say $x =~= $y :tolerance(.1);
=end code

However, this is not yet implemented. The same effect can be achieved by
assigning to $*TOLERANCE.

    {
        my $*TOLERANCE = .1;
        say 11 =~= 10;        # OUTPUT: «True␤»
    }

Note that setting $*TOLERANCE = 0 will cause all comparisons to fail.

    {
        my $*TOLERANCE = 0;
        say 1 =~= 1;          # OUTPUT: «False␤»
    }

=head1 Tight AND Precedence

=head2 infix C«&&»

Returns the first argument that evaluates to C<False> in boolean context,
otherwise returns the last argument.

Note that this short-circuits, i.e. if one of the arguments evaluates to a
false value, the arguments to the right are never evaluated.

    sub a { 1 }
    sub b { 0 }
    sub c { die "never called" };
    say a() && b() && c();      # OUTPUT: «0␤»

=head1 Tight OR Precedence

=head2 infix C«||»

Returns the first argument that evaluates to C<True> in boolean context,
otherwise returns the last argument.

Note that this short-circuits; i.e., if one of the arguments evaluates to a
true value, the remaining arguments are not evaluated.

    sub a { 0 }
    sub b { 1 }
    sub c { die "never called" };
    say a() || b() || c();      # OUTPUT: «1␤»

=head2 infix C«^^»

X<Short-circuit exclusive-or>. Returns the true argument if there
is one (and only one). Returns the last argument if all arguments are false.
Returns C<Nil> when more than one argument is true.

This operator short-circuits in the sense that it does not evaluate
any arguments after a 2nd true result.

    say 0 ^^ 42;                             # OUTPUT: «42␤»
    say '' ^^ 0;                             # OUTPUT: «0␤»
    say 0 ^^ 42 ^^ 1 ^^ die "never called";  # OUTPUT: «␤»

Note that the semantics of this operator may not be what you assume: infix C«^^»
flips to the first true value it finds and then flips to Nil I<forever> after the
second, no matter how many more true values there are. (In other words, it has
"find the one true value" semantics, not "boolean parity" semantics.)

=head2 infix C«//»

X<Defined-or operator>. Returns the first defined operand, or else the last
operand. Short-circuits.

    say Any // 0 // 42;         # OUTPUT: «0␤»

=head2 infix C«min»

Returns the smallest of the arguments, as determined by L<cmp> semantics.

    my $foo = 42;
    $foo min= 0   # read as: $foo decreases to 0

=head2 infix C«max»

Returns the largest of the arguments, as determined by L<cmp> semantics.

    my $foo = -42;
    $foo max= 0   # read as: $foo increases to 0

=head2 infix C«minmax»

Returns the L<Range|/type/Range> starting from the lowest to the highest of the values,
as determined by the L<cmp> semantics.
For instance:

=begin code
# numeric comparison
10 minmax 3;     # 3..10

# string comparison
'10' minmax '3'; # "10".."3"
'z' minmax 'k';  # "k".."z"
=end code

If the lowest and highest values coincide, the operator returns a L<Range>
made by the same value:

=begin code
1 minmax 1;  # 1..1
=end code

When applied to L<List>s, the operator evaluates the lowest and highest values
among all available values:

=begin code
(10,20,30) minmax (0,11,22,33);       # 0..33
('a','b','z') minmax ('c','d','w');   # "a".."z"
=end code

Similarly, when applied to L<Hash>es, it performs a L<cmp> way comparison:

=begin code
my %winner = points => 30, misses => 10;
my %loser = points => 20, misses => 10;
%winner cmp %loser;      # More
%winner minmax %loser;
# ${:misses(10), :points(20)}..${:misses(10), :points(30)}
=end code

=head1 Conditional Operator Precedence

=head2 infix C<?? !!>

X<Ternary operator>, X<conditional operator>.

C<$condition ?? $true !! $false> evaluates and returns the expression from the
C<$true> branch if C<$condition> is a true value. Otherwise it evaluates and
returns the C<$false> branch.

=head2 infix C«ff»

    sub infix:<ff>(Mu $a, Mu $b)

X<Flipflop operator>.

Compares both arguments to C<$_> (that is, C<$_ ~~ $a> and C<$_ ~~
$b>). Evaluates to C<False> until the left-hand smartmatch is C<True>, at which
point it evaluates to C<True> until the right-hand smartmatch is C<True>.

In effect, the left-hand argument is the "start" condition and the right-hand
is the "stop" condition. This construct is typically used to pick up only a
certain section of lines. For example:

=begin code :allow<B V>
my $excerpt = q:to/END/;
Here's some unimportant text.
V<=>begin code
    This code block is what we're after.
    We'll use 'ff' to get it.
V<=>end code
More unimportant text.
END

my @codelines = gather for $excerpt.lines {
    take $_ if B<"=begin code" ff "=end code">
}

# this will print four lines, starting with "=begin code" and ending with
# "=end code"
say @codelines.join("\n");
=end code

After matching the start condition, the operator will then match the same C<$_>
to the stop condition and act accordingly if successful. In this example, only
the first element is printed:

    for <AB C D B E F> {
        say $_ if /A/ ff /B/;  # OUTPUT: «AB␤»
    }

If you only want to test against a start condition and have no stop condition,
C<*> can be used as the "stop" condition.

    for <A B C D E> {
        say $_ if /C/ ff *;    # OUTPUT: «C␤D␤E␤»
    }

For the sed-like version, which does I<not> try C<$_> on the stop condition
after succeeding on the start condition, see L<C<fff>>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«^ff»

    sub infix:<^ff>(Mu $a, Mu $b)

Works like L<C<ff>>, except it does not return C<True> for items matching the
start condition (including items also matching the stop condition).

A comparison:

    my @list = <A B C>;
    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^ff /C/ for @list;   # OUTPUT: «B␤C␤»

The sed-like version can be found in L<C<^fff>|/routine/^fff>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«ff^»

    sub infix:<ff^>(Mu $a, Mu $b)

Works like L<C<ff>>, except it does not return C<True> for items matching the
stop condition (including items that first matched the start condition).

    my @list = <A B C>;
    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ff^ /C/ for @list;   # OUTPUT: «A␤B␤»

The sed-like version can be found in L<C<fff^>>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«^ff^»

    sub infix:<^ff^>(Mu $a, Mu $b)

Works like L<C<ff>>, except it does not return C<True> for items matching either
the stop or start condition (or both).

    my @list = <A B C>;
    say $_ if /A/ ff /C/ for @list;    # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^ff^ /C/ for @list;  # OUTPUT: «B␤»

The sed-like version can be found in L<C<^fff^>|/routine/^fff^>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«fff»

    sub infix:<fff>(Mu $a, Mu $b)

Performs a sed-like flipflop operation, wherein it returns C<False> until the
left argument smartmatches against C<$_>, then returns C<True> until
the right argument smartmatches against C<$_>.

Works similarly to L<C<ff>>, except that it only tries one argument per
invocation. That is, if C<$_> smartmatches the left argument, C<fff> will B<not>
then try to match that same C<$_> against the right argument.

    for <AB C D B E F> {
        say $_ if /A/ fff /B/;         # OUTPUT: «AB␤C␤D␤B␤»
    }

The non-sed-like flipflop (which after successfully matching the left argument
against C<$_> will try that same C<$_> against the right argument and act
accordingly). See L<C<ff>>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«^fff»

    sub infix:<^fff>(Mu $a, Mu $b)

Like L<C<fff>>, except it does not return true for matches to the left argument.

    my @list = <A B C>;
    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^fff /C/ for @list;  # OUTPUT: «B␤C␤»

For the non-sed version, see L<C<^ff>|/routine/^ff>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«fff^»

    sub infix:<fff^>(Mu $a, Mu $b)

Like L<C<fff>>, except it does not return true for matches to the right argument.

    my @list = <A B C>;
    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ fff^ /C/ for @list;  # OUTPUT: «A␤B␤»

For the non-sed version, see L<C<ff^>>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head2 infix C«^fff^»

    sub infix:<^fff^>(Mu $a, Mu $b)

Like L<C<fff>>, except it does not return true for matches to either the left or
right argument.

    my @list = <A B C>;
    say $_ if /A/ fff /C/ for @list;   # OUTPUT: «A␤B␤C␤»
    say $_ if /A/ ^fff^ /C/ for @list; # OUTPUT: «B␤»

For the non-sed version, see L<C<^ff^>|/routine/^ff^>.

This operator cannot be overloaded, as it's handled specially by the compiler.

=head1 Item Assignment Precedence

=head2 infix C«=»

=begin code :skip-test
sub infix:<=>(Mu $a is rw, Mu $b)
=end code

X<Item assignment operator>.

Places the value of the right-hand side into the container on the left-hand
side. Its exact semantics are left to the container type on the left-hand side.

(Note that item assignment and list assignment have different precedence
levels, and the syntax of the left-hand side decides whether an equal sign
C<=> is parsed as item assignment or list assignment operator).

=head2 infix C«=>»

    sub infix:«=>»($key, Mu $value --> Pair:D)

L<Pair> constructor.X<|pair constructor>

Constructs a L<Pair> object with the left-hand side as the key and the
right-hand side as the value.

Note that the C<< => >> operator is syntactically special-cased, in that
it allows unquoted identifier on the left-hand side.

    my $p = a => 1;
    say $p.key;         # OUTPUT: «a␤»
    say $p.value;       # OUTPUT: «1␤»

A L<Pair> within an argument list with an unquoted identifier on the left
is interpreted as a named argument.

See L<the Terms language documentation|/language/terms#Pair> for more ways to
create C<Pair> objects.

=head1 Loose Unary Precedence

=head2 prefix C«not»

    multi sub prefix:<not>(Mu $x --> Bool:D)

Evaluates its argument in boolean context (and thus collapses L<Junction>s),
and negates the result. Please note that C<not> is easy to misuse. See
L<traps|/language/traps#Loose_boolean_operators>.


=head2 prefix C«so»

    multi sub prefix:<so>(Mu $x --> Bool:D)

Evaluates its argument in boolean context (and thus collapses L<Junction>s),
and returns the result.

=head1 Comma Operator Precedence

=head2 infix C«,»

    sub infix:<,>(*@a --> List:D) is assoc<list>

Constructs a L<List> from its arguments. Also used syntactically as the
separator of arguments in calls.

=head2 infix C«:»

Used as an argument separator just like infix C<,> and marks the argument to
its left as the invocant. That turns what would otherwise be a function call
into a method call.

    substr('abc': 1);       # same as 'abc'.substr(1)

Infix C<:> is only allowed after the first argument of a non-method call. In
other positions, it's a syntax error.

=head1 List Infix Precedence

=head2 infix C«Z»

    sub infix:<Z>(**@lists --> Seq:D) is assoc<chain>

X<Zip operator>.

Interleaves the lists passed to C<Z> like a zipper, stopping as soon as the
first input list is exhausted. The returned C<Seq> contains a nested list with
values for all C<Z> operators in a chain.

    say (1, 2 Z <a b c> Z <+ ->).perl;  # OUTPUT: «((1, "a", "+"), (2, "b", "-")).Seq␤»
    for <a b c> Z <1 2 3> -> [$l, $r] {
        say "$l:$r"
    }
    # OUTPUT: «a:1␤b:2␤c:3␤»

The C<Z> operator also exists as a meta operator, in which case the inner
lists are replaced by the value from applying the operator to the
list:

    say 100, 200 Z+ 42, 23;             # OUTPUT: «(142 223)␤»
    say 1..3 Z~ <a b c> Z~ 'x' xx 3;    # OUTPUT: «(1ax 2bx 3cx)␤»

=head2 infix C«X»

    sub infix:<X>(**@lists --> List:D)

Creates a cross product from all the lists, order so that the rightmost
elements vary most rapidly:X<|cross product operator>

    1..3 X <a b c> X 9
    # produces ((1 a 9) (1 b 9) (1 c 9)
    #           (2 a 9) (2 b 9) (2 c 9)
    #           (3 a 9) (3 b 9) (3 c 9))

The C<X> operator also exists as a meta operator, in which case the inner
lists are replaced by the value from applying the operator to the
list:

    1..3 X~ <a b c> X~ 9
    # produces (1a9 1b9 1c9 2a9 2b9 2c9 3a9 3b9 3c9)

=head2 infix C«...»
X<|...,operators>X<|...^,operators>X<|…,operators>X<|…^,operators>X<|lazy list,…>

    multi sub infix:<...>(**@) is assoc<list>
    multi sub infix:<...^>(**@) is assoc<list>

The X<sequence operator> is a generic operator to produce lazy lists.

It can have initial elements and a generator on the left-hand side and an
endpoint on the right-hand side.

The sequence operator invokes the generator with as many arguments as
necessary. The arguments are taken from the initial elements and the already
generated elements.

The default generator is C<*.>L<succ> or C<*.>L<pred>, depending on how
the end points compare:

    say 1 ... 4;        # OUTPUT: «(1 2 3 4)␤»
    say 4 ... 1;        # OUTPUT: «(4 3 2 1)␤»
    say 'a' ... 'e';    # OUTPUT: «(a b c d e)␤»
    say 'e' ... 'a';    # OUTPUT: «(e d c b a)␤»

An endpoint of C<*> (L<Whatever>) generates an infinite sequence,
with a default generator of *.succ

    say (1 ... *)[^5];  # OUTPUT: «(1 2 3 4 5)␤»


Custom generators are the last argument before the '...' operator.
This one takes two arguments, and generates the Fibonacci numbers

    say (1, 1, -> $a, $b { $a + $b } ... *)[^8];    # OUTPUT: «(1 1 2 3 5 8 13 21)␤»
    # same but shorter
    say (1, 1, *+* ... *)[^8];                      # OUTPUT: «(1 1 2 3 5 8 13 21)␤»

Of course the generator can also take only one argument.

    say 5, { $_ * 2 } ... 40;                       # OUTPUT: «5 10 20 40␤»

There must be at least as many initial elements as arguments to the generator.

Without a generator and with more than one initial element and all initial
elements numeric, the sequence operator tries to deduce the generator. It
knows about arithmetic and geometric sequences.

    say 2, 4, 6 ... 12;     # OUTPUT: «(2 4 6 8 10 12)␤»
    say 1, 2, 4 ... 32;     # OUTPUT: «(1 2 4 8 16 32)␤»

If the endpoint is not C<*>, it's smart-matched against each generated
element and the sequence is terminated when the smart-match succeeded.
For the C<...> operator, the final element is included, for the C<...^>
operator it's excluded.

This allows you to write

    say 1, 1, *+* ...^ *>= 100;

To generate all Fibonacci numbers up to but excluding 100.

The C<...> operators consider the initial values as "generated elements" as
well, so the are also checked against the endpoint:

    my $end = 4;
    say 1, 2, 4, 8, 16 ... $end;
    # OUTPUT: «(1 2 4)␤»

=head1 List Prefix Precedence

=head2 infix C«=»

X<List assignment operator>. Its exact semantics are left to the container type on the
left-hand side. See L<Array> and L<Hash> for common cases.

The distinction between item assignment and list assignment is determined by
the parser depending on the syntax of the left-hand side.

=head2 infix C«:=»

X<Binding operator>. Whereas C<$x = $y> puts the value in C<$y> into C<$x>, C<$x :=
$y> makes C<$x> and C<$y> the same thing.

    my $a = 42;
    my $b = $a;
    $b++;
    say $a;

This will output 42, because C<$a> and C<$b> both contained the number
C<42>, but the L<containers|/language/containers#Binding> were
different.

    my $a = 42;
    my $b := $a;
    $b++;
    say $a;

This will output 43, since C<$b> and C<$a> both represented the same
object.

Please note that C<:=> is a compile time construct. As such it can not be
referred to at runtime and thus can't be used as an argument to meta operators.

=head2 infix C«::=»

X<Read-only binding operator>, not yet implemented in Rakudo.
See L<C<infix :=>|:=>.

=head2 listop C«...»

X<|stub operator>
The I<yada, yada, yada> operator or I<stub> operator. If it's the only
statement in a routine or type, it marks that routine or type as a stub
(which is significant in the context of pre-declaring types and composing
roles).

If the C<...> statement is executed, it calls L<fail|/routine/fail>, with the default
message C<stub code executed>.

=head2 listop C«!!!»

X<Fatal stub operator>.

If it's the only
statement in a routine or type, it marks that routine or type as a stub
(which is significant in the context of pre-declaring types and composing
roles).

If the C<!!!> statement is executed, it calls L<die|/routine/die>, with the default
message C<stub code executed>.

=head2 listop C«???»

X<Admonitory stub operator>.

If it's the only
statement in a routine or type, it marks that routine or type as a stub
(which is significant in the context of pre-declaring types and composing
roles).

If the C<???> statement is executed, it calls L<warn|/routine/warn>, with the default
message C<stub code executed>.

=head2 Reduction operators

Any infix operator (except for non-associating operators) can be
surrounded by square brackets in term position to create a list operator
that reduces using that operation.

    say [+] 1, 2, 3;      # 1 + 2 + 3 = 6
    my @a = (5, 6);
    say [*] @a;           # 5 * 6 = 30

Reduction operators have the same associativity as the operators they are based on.

    say [-] 4, 3, 2;      # 4-3-2 = (4-3)-2 = -1
    say [**] 4, 3, 2;     # 4**3**2 = 4**(3**2) = 262144

=head1 Loose AND precedence

=head2 infix C«and»

Same as L<#infix &&>, except with looser precedence.

Short-circuits so that it returns the first operand that evaluates to C<False>, otherwise
returns the last operand. Note that C<and> is easy
to misuse. See L<traps|/language/traps#Loose_boolean_operators>.

=head2 infix C«andthen»

Returns L«C<Empty>|/type/Slip#index-entry-Empty-Empty» upon encountering
the first L<undefined|/routine/defined> argument, otherwise the last argument.
Last argument
is returned as-is, without being checked for definedness at all.
Short-circuits. The result of the left side is bound to C<$_> for the
right side, or passed as arguments if the right side is a
L«C<Callable>|/type/Callable», whose L<count> must be C<0> or C<1>.

A handy use of this operator is to alias a routine's return value to C<$_> and
to do additional manipulation with it, such as printing or returning it to
caller. Since the C<andthen> operator short-circuits, statements on the
right-hand side won't get executed, unless left-hand side is defined (tip:
L<Failures|/type/Failure> are never defined, so you can handle them with
this operator).

    sub load-data {
        rand  > .5 or return; # simulated load data failure; return Nil
        (rand > .3 ?? 'error' !! 'good data') xx 10 # our loaded data
    }
    load-data.first: /good/ andthen say "$_ is good";
    # OUTPUT: «(good data is good)␤»

    load-data() andthen .return; # return loaded data, if it's defined
    die "Failed to load data!!";

The above example will print C<good data is good> only if the subroutine
returned any items that match C</good/> and will die unless loading data
returned a defined value. The aliasing behaviour lets us pipe the values across
the operator.

The C<andthen> operator is a close relative of
L«C<with> statement modifier|/syntax/with orwith without», and some compilers
compile C<with> to C<andthen>, meaning these two lines have equivalent
behaviour:

    .say with 42;
    42 andthen .say;

=head2 infix C«notandthen»

Returns L«C<Empty>|/type/Slip#index-entry-Empty-Empty» upon encountering
the first L<defined|/routine/defined> argument, otherwise the last argument.
Last argument is returned as-is, without being checked for definedness at all.
Short-circuits. The result of the left side is bound to C<$_> for the
right side, or passed as arguments if the right side is a
L«C<Callable>|/type/Callable», whose L<count> must be C<0> or C<1>.

At first glance, L<notandthen> might appear to be the same thing as the L<orelse>
operator. The difference is subtle: L<notandthen> returns
L«C<Empty>|/type/Slip#index-entry-Empty-Empty» when it encounters a
L<defined> item (that isn't the last item), whereas L<orelse> returns that
item. In other words, L<notandthen> is a means to act when items aren't
defined, whereas L<orelse> is a means to obtain the first defined item:

=begin code
    sub all-sensors-down     { [notandthen] |@_, True             }
    sub first-working-sensor { [orelse]     |@_, 'default sensor' }

    all-sensors-down Nil, Nil, Nil
      and say 'OMG! All sensors are down!'; # OUTPUT:«OMG! All sensors are down!␤»
    say first-working-sensor Nil, Nil, Nil; # OUTPUT:«default sensor␤»

    all-sensors-down Nil, 42, Nil
      and say 'OMG! All sensors are down!'; # No output
    say first-working-sensor Nil, 42, Nil;  # OUTPUT:«42␤»
=end code

The C<andthen> operator is a close relative of
L«C<without> statement modifier|/syntax/with orwith without», and some compilers
compile C<without> to C<notandthen>, meaning these two lines have equivalent
behaviour:

=begin code
    sub good-things { fail }

    'boo'.say without good-things;
    good-things() notandthen 'boo'.say;
=end code

=head1 Loose OR Precedence

=head2 infix C«or»

Same as L<infix C<||>|#infix || >, except with looser precedence.

Returns the first argument that evaluates to C<True> in boolean context,
or otherwise the last argument, it short-circuits. Please note that C<or> is easy
to misuse. See L<traps|/language/traps#Loose_boolean_operators>.


=head2 infix C«orelse»

Similar to C<infix //>, except with looser precedence and C<$_> aliasing.

Returns the first defined argument, or else the last argument. Last argument
is returned as-is, without being checked for definedness at all.
Short-circuits. The result of the left side is bound to
C<$_> for the right side, or passed as an argument if the right side is a
L«C<Callable>|/type/Callable», whose L<count> must be C<0> or C<1>.

This operator is useful for handling L<Failures|/type/Failure> returned by
routines since the expected value is usually L<defined>
and L<Failure> never is:

    sub meows { ++$ < 4 ?? fail 'out of meows!' !! '🐱' }

    sub meows-processor1 { meows() orelse .return } # return handled Failure
    sub meows-processor2 { meows() orelse fail $_ } # return re-armed Failure
    sub meows-processor3 {
        # Use non-Failure output, or else print a message that stuff's wrong
        meows() andthen .say orelse ‘something's wrong’.say;
    }

    say "{.^name}, {.handled}"  # OUTPUT: «Failure, True␤»
        given meows-processor1;
    say "{.^name}, {.handled}"  # OUTPUT: «Failure, False␤»
        given meows-processor2;
    meows-processor3;           # OUTPUT: «something's wrong␤»
    meows-processor3;           # OUTPUT: «🐱␤»

=head2 infix C«xor»

Same as L<infix C<^^>|#infix ^^>, except with looser precedence.

Returns the operand that evaluates to C<True> in boolean context, if and
only if the other operand evaluates to C<False> in boolean context. If
both operands evaluate to C<False>, returns the last argument. If both
operands evaluate to C<True>, returns C<Nil>.

When chaining, returns the operand that evaluates to C<True>, if and
only if there is one such operand. If more than one operand is true,
it short-circuits after evaluating the second and returns C<Nil>. If all
operands are false, returns the last one.

=head1 Sequencer Precedence

=head2 infix C«==>»

This X<feed> operator takes the result from the left and passes it to the
next (right) routine as the last parameter.

The precedence is very loose so you will need to use parentheses to
assign the result or you can even just use another feed operator! In the
case of routines/methods that take a single argument or where the first argument
is a block, it's often required that you call with parentheses (though this
is not required for the very last routine/method).

This  "traditional" structure, read bottom-to-top, with the last two
lines creating the data structure that is going to be processed

    my @fractions = <TWO THREE FOUR FIVE SEVEN> »~» " " X~ <FIFTHS SIXTHS EIGHTHS>;
    my @result = map { .uniparse },                    # (3) Converts to unicode
        grep { .uniparse },                            # (2) Checks if it parses
        map( {"VULGAR FRACTION " ~ $^þ }, @fractions); # (1) Adds string to input

    # @result is [⅖ ⅗ ⅜ ⅘ ⅚ ⅝ ⅞]

Now we use the feed operator (left-to-right) with parentheses, read top-to-bottom

    my @result = (
        <TWO THREE FOUR FIVE SEVEN> »~» " " X~ <FIFTHS SIXTHS EIGHTHS> # (1) Input
        ==> map( {"VULGAR FRACTION " ~ $^þ } )                         # (2) Converts to Unicode name
        ==> grep({ .uniparse })                                        # (3) Filters only real names
        ==> map( { .uniparse} );                                       # (4) Converts to unicode
    );

For illustration, method chaining equivalent, read top-to-bottom, using the same sequence as above

    my @result = ( <TWO THREE FOUR FIVE SEVEN> »~» " " X~ <FIFTHS SIXTHS EIGHTHS>)
        .map( {"VULGAR FRACTION " ~ $^þ } )
        .grep({ .uniparse })
        .map({ .uniparse });

Although in this particular case the result is the same, the feed operator C«==>» more clearly
    shows intent with arrow pointing the data flow.  To assign without
    the need of parentheses use another feed operator

    my @result;
    <people of earth>
        ==> map({ .tc })
        ==> grep /<[PE]>/
        ==> sort()
        ==> @result;

It can be useful to capture a partial result, however, unlike the
    leftward feed operator, it does require parentheses or a semicolon

    my @result;
    <people of earth>
        ==> map({ .tc })
        ==> my @caps; @caps   # also could wrap in parentheses instead
        ==> grep /<[PE]>/
        ==> sort()
        ==> @result;

The feed operator lets you construct method-chaining-like patterns out of
routines and the results of methods on unrelated data. In method-chaining,
you are restricted to the methods available on the data or the result of
previous method call. With feed operators, that restriction is gone.
The resulting code could also be seen to be more readable than a series of
method calls broken over multiple lines.

Note: In the future, this operator will see some change as it gains the
ability to run list operations in parallel. It will enforce that the
B<left> operand is enclosable as a closure (that can be cloned and run in
a subthread).

=head2 infix C«<==»

This X<leftward feed> operator takes the result from the right and passes
it to the previous (left) routine as the last parameter. This
elucidates the right-to-left dataflow for a series of list manipulating
functions.

    # Traditional structure, read bottom-to-top
    my @result =
        sort                   # (4) Sort, result is <Earth People>
        grep { /<[PE]>/ },     # (3) Look for P or E
        map { .tc },           # (2) Capitalize the words
        <people of earth>;     # (1) Start with the input

    # Feed (right-to-left) with parentheses, read bottom-to-top
    my @result = (
        sort()                 # (4) Sort, result is <Earth People>
        <== grep({ /<[PE]>/ }) # (3) Look for P or E
        <== map({ .tc })       # (2) Capitalize the words
        <== <people of earth>  # (1) Start with the input
    );

    # To assign without parentheses, use another feed operator
    my @result
        <== sort()              # (4) Sort, result is <Earth People>
        <== grep({ /<[PE]>/ })  # (3) Look for P or E
        <== map({ .tc })        # (2) Capitalize the words
        <== <people of earth>;  # (1) Start with the input

    # It can be useful to capture a partial result
    my @result
        <== sort()
        <== grep({ /<[PE]>/ })
        <== my @caps            # unlike ==>, there's no need for additional statement
        <== map({ .tc })
        <== <people of earth>;

Unlike the rightward feed operator, the result is not closely mappable
to method-chaining. However, compared to the traditional structure above
where each argument is separated by a line, the resulting code is more
demonstrative than commas. The leftward feed operator also allows you
to "break into" the statement and capture an intermediary result which
can be extremely useful for debugging or to take that result and create
another variation on the final result.

Note: In the future, this operator will see some change as it gains the
ability to run list operations in parallel. It will enforce that the
B<right> operand is enclosable as a closure (that can be cloned and run in
a subthread).

=end pod

# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6
